// 窗口运行完毕运行显示倒计时函数
window.onload = function() {
    displayClosestEvents();
    const nicknameElement = document.querySelector('#user');
    const nickname = sessionStorage.getItem('nickname');
    if (nickname) {
        nicknameElement.textContent = nickname;
    } else {
        nicknameElement.textContent = "登录|注册";
    }
};

// 秒杀信息
function displayClosestEvents() {
    const eventTimes = ["00:00", "02:00", "04:00", "06:00", "08:00", "10:00", "12:00", "14:00", "16:00", "18:00", "20:00", "22:00"];
    const currentTime = new Date();

    const closestEvents = findClosestEvents(eventTimes, currentTime);

    createEvents(closestEvents);
    setTimeout(function() {
        // 获取所有的event元素
        const events = document.querySelectorAll('.event');

        // 遍历每个event元素
        events.forEach(function(event) {
            event.style.display = 'block';
            updateStatus();
            // 获取当前event元素中的status标签
            const statusElement = event.querySelector('.status');
            // 检查status标签的内容
            if (statusElement && statusElement.textContent === '正在秒杀') {
                // 模拟点击事件
                event.click();
            }
        });
    },5);
    // 绑定点击事件
    bindClickEvents();
}

// 新建倒计时
function createEvents(eventsToShow) {
    const schedule = document.getElementById('schedule');
    eventsToShow.forEach(eventTime => {
        const eventDiv = document.createElement('div');
        eventDiv.className = 'event';

        const h2 = document.createElement('h2');
        h2.textContent = eventTime;

        const status = document.createElement('p');
        status.className = 'status';

        const countdown = document.createElement('p');
        countdown.className = 'countdown';

        eventDiv.appendChild(h2);
        eventDiv.appendChild(status);
        eventDiv.appendChild(countdown);

        schedule.appendChild(eventDiv);

    });
}


// 计算秒杀时间
function findClosestEvents(events, currentTime) {
    const timeDiffs = events.map(eventTime => {
        const eventDate = new Date();
        const [hours, minutes] = eventTime.split(':');
        eventDate.setHours(hours, minutes, 0, 0);
        return { eventTime, diff: Math.abs(eventDate - currentTime) };
    });

    timeDiffs.sort((a, b) => a.diff - b.diff);

    const closestEventIndex = events.indexOf(timeDiffs[0].eventTime);
    const previousEventIndex = (closestEventIndex - 1 + events.length) % events.length;
    const nextEventIndex = (closestEventIndex + 1) % events.length;
    return [events[previousEventIndex], events[closestEventIndex], events[nextEventIndex]];
}

// 绑定点击事件，显示秒杀时间和状态
function bindClickEvents() {
    document.querySelectorAll('.event').forEach(item => {
        item.addEventListener('click', () => {
            document.querySelectorAll('.event').forEach(el => {
                el.classList.remove('red');
                el.querySelector('.countdown').style.display = 'none';
            });
            item.classList.add('red');
            item.querySelector('.countdown').style.display = 'block';
            updateCountdown(item);
            // 获取 h2 元素
            const h2Element = item.querySelector('h2');
            // 获取 h2 元素的文本内容
            const h2Value = h2Element.textContent;
            document.querySelector('.banner2-box').innerHTML="";
            $.ajax({
                url: "/goods",
                method: "get",
                data: {num: 5, time: h2Value},
                dataType: "json",
                success: function(dataString) {
                    show(dataString);
                    let prices = document.querySelectorAll('.price2');
                    let buttons = document.querySelectorAll('.buy');
                    $.ajax({
                        url: "/goods",
                        method: "get",
                        data: {num: 6, time: h2Value},
                        dataType: "text",
                        success: function(data) {
                            const pricesToSet = JSON.parse(data);
                            if (prices.length === pricesToSet.length) {
                                // 遍历.price2元素并设置它们的文本
                                prices.forEach((price, index) => {
                                    price.textContent = pricesToSet[index];
                                });
                            }
                            // 遍历.buy元素并修改它们的文本
                            buttons.forEach((button) => {
                                // 获取event red元素
                                const events = document.querySelector('.event.red');
                                // 获取当前event元素中的status标签
                                const statusElement = events.querySelector('.status');
                                // 检查status标签的内容
                                if (statusElement && statusElement.textContent === '即将开始') {
                                    button.textContent = '即将开始';
                                    button.style = "background-color:gray;"
                                }
                            });
                        }
                    })
                }
            });
        });
    });
}

// 更新倒计时
function updateCountdown(clickedEvent) {
    const currentTime = new Date();
    const clickedTime = new Date();
    const clickedHour = parseInt(clickedEvent.querySelector('h2').textContent.split(':')[0]);

    clickedTime.setHours(clickedHour, 0, 0, 0);

    if (currentTime >= clickedTime && currentTime < new Date(clickedTime.getTime() + 60 * 60 * 1000)) {
        const timeLeft = new Date(clickedTime.getTime() + 60 * 60 * 1000 - currentTime.getTime());
        const minutes = String(timeLeft.getMinutes()).padStart(2, '0');
        const seconds = String(timeLeft.getSeconds()).padStart(2, '0');
        clickedEvent.querySelector('.countdown').textContent = `距结束00:${minutes}:${seconds}`;
        clickedEvent.querySelector('.status').textContent = '正在秒杀';
    } else {
        if (currentTime >= clickedTime) {
            clickedTime.setDate(clickedTime.getDate() + 1);
        }
        const timeUntil = new Date(clickedTime.getTime() - currentTime.getTime());
        const hours = String(Math.floor(timeUntil / (60 * 60 * 1000))).padStart(2, '0');
        const minutes = String(Math.floor((timeUntil % (60 * 60 * 1000)) / (60 * 1000))).padStart(2, '0');
        const seconds = String(Math.floor((timeUntil % (60 * 1000)) / 1000)).padStart(2, '0');
        clickedEvent.querySelector('.countdown').textContent = `距开始${hours}:${minutes}:${seconds}`;
        clickedEvent.querySelector('.status').textContent = '即将开始';
    }
}

// 更新状态
function updateStatus() {
    const currentTime = new Date();
    document.querySelectorAll('.event').forEach(event => {
        const eventTime = new Date();
        const eventHour = parseInt(event.querySelector('h2').textContent.split(':')[0]);
        eventTime.setHours(eventHour, 0, 0, 0);
        if (currentTime >= eventTime && currentTime < new Date(eventTime.getTime() + 60 * 60 * 1000)) {
            event.querySelector('.status').textContent = '正在秒杀';
        } else {
            event.querySelector('.status').textContent = '即将开始';
        }
    });
}

// 自动更新倒计时
setInterval(() => {
    document.querySelectorAll('.event.red').forEach(event => {
        updateCountdown(event);
    });
}, 1000);